import React, { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '../ui/card';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Badge } from '../ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { 
  Search, 
  Filter, 
  ShoppingCart, 
  Clock, 
  Users, 
  Book,
  CheckCircle,
  XCircle,
  AlertTriangle
} from 'lucide-react';

interface Course {
  id: string;
  name: string;
  teacher: string;
  credits: number;
  time: string;
  location: string;
  capacity: number;
  enrolled: number;
  category: string;
  description: string;
}

export function CourseSelection() {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [cart, setCart] = useState<Course[]>([]);

  const availableCourses: Course[] = [
    {
      id: '1',
      name: '人工智能导论',
      teacher: '张教授',
      credits: 3,
      time: '周一 3-4节',
      location: '教学楼A-101',
      capacity: 60,
      enrolled: 45,
      category: '专业必修',
      description: '介绍人工智能的基本概念、发展历程和应用领域'
    },
    {
      id: '2',
      name: '数据结构与算法',
      teacher: '李老师',
      credits: 4,
      time: '周二 1-2节',
      location: '教学楼B-203',
      capacity: 80,
      enrolled: 78,
      category: '专业必修',
      description: '学习基本数据结构和算法设计与分析'
    },
    {
      id: '3',
      name: '英语口语',
      teacher: '王老师',
      credits: 2,
      time: '周三 5-6节',
      location: '语音教室C-301',
      capacity: 30,
      enrolled: 25,
      category: '通识选修',
      description: '提高英语口语表达能力和交流技巧'
    },
    {
      id: '4',
      name: '计算机网络',
      teacher: '刘教授',
      credits: 3,
      time: '周四 3-4节',
      location: '实验楼D-401',
      capacity: 50,
      enrolled: 35,
      category: '专业必修',
      description: '学习计算机网络的基本原理和协议'
    }
  ];

  const selectedCourses: Course[] = [
    {
      id: 's1',
      name: '高等数学A',
      teacher: '陈教授',
      credits: 5,
      time: '周一 1-2节',
      location: '教学楼A-201',
      capacity: 100,
      enrolled: 95,
      category: '公共必修',
      description: '数学分析基础课程'
    }
  ];

  const addToCart = (course: Course) => {
    if (!cart.find(c => c.id === course.id)) {
      setCart([...cart, course]);
    }
  };

  const removeFromCart = (courseId: string) => {
    setCart(cart.filter(c => c.id !== courseId));
  };

  const getTotalCredits = () => {
    return cart.reduce((total, course) => total + course.credits, 0) + 
           selectedCourses.reduce((total, course) => total + course.credits, 0);
  };

  const getAvailableSlots = (course: Course) => {
    return course.capacity - course.enrolled;
  };

  const getStatusBadge = (course: Course) => {
    const available = getAvailableSlots(course);
    if (available === 0) {
      return <Badge variant="destructive">已满</Badge>;
    } else if (available <= 5) {
      return <Badge variant="outline">紧张</Badge>;
    } else {
      return <Badge variant="secondary">可选</Badge>;
    }
  };

  const filteredCourses = availableCourses.filter(course => {
    const matchesSearch = course.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         course.teacher.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesCategory = selectedCategory === 'all' || course.category === selectedCategory;
    return matchesSearch && matchesCategory;
  });

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-medium">选课管理</h1>
        <Badge variant="outline" className="text-lg px-3 py-1">
          当前学分: {getTotalCredits()}/25
        </Badge>
      </div>

      <Tabs defaultValue="selection" className="space-y-4">
        <TabsList>
          <TabsTrigger value="selection">课程选择</TabsTrigger>
          <TabsTrigger value="cart">选课车 ({cart.length})</TabsTrigger>
          <TabsTrigger value="selected">已选课程</TabsTrigger>
        </TabsList>

        <TabsContent value="selection" className="space-y-4">
          {/* Search and Filter */}
          <Card>
            <CardContent className="p-4">
              <div className="flex gap-4">
                <div className="relative flex-1">
                  <Search className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                  <Input
                    placeholder="搜索课程名称或教师姓名..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="pl-10"
                  />
                </div>
                <Select value={selectedCategory} onValueChange={setSelectedCategory}>
                  <SelectTrigger className="w-48">
                    <Filter className="mr-2 h-4 w-4" />
                    <SelectValue placeholder="课程类别" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部类别</SelectItem>
                    <SelectItem value="公共必修">公共必修</SelectItem>
                    <SelectItem value="专业必修">专业必修</SelectItem>
                    <SelectItem value="专业选修">专业选修</SelectItem>
                    <SelectItem value="通识选修">通识选修</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </CardContent>
          </Card>

          {/* Course List */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {filteredCourses.map((course) => (
              <Card key={course.id} className="hover:shadow-md transition-shadow">
                <CardHeader>
                  <div className="flex justify-between items-start">
                    <div>
                      <CardTitle className="text-lg">{course.name}</CardTitle>
                      <p className="text-sm text-muted-foreground">{course.teacher}</p>
                    </div>
                    {getStatusBadge(course)}
                  </div>
                </CardHeader>
                <CardContent className="space-y-3">
                  <p className="text-sm">{course.description}</p>
                  
                  <div className="grid grid-cols-2 gap-2 text-sm">
                    <div className="flex items-center">
                      <Book className="mr-1 h-3 w-3" />
                      {course.credits}学分
                    </div>
                    <div className="flex items-center">
                      <Clock className="mr-1 h-3 w-3" />
                      {course.time}
                    </div>
                    <div className="flex items-center">
                      <Users className="mr-1 h-3 w-3" />
                      {course.enrolled}/{course.capacity}
                    </div>
                    <div className="text-muted-foreground">
                      {course.location}
                    </div>
                  </div>

                  <div className="flex justify-between items-center pt-2">
                    <Badge variant="outline">{course.category}</Badge>
                    <Button
                      size="sm"
                      onClick={() => addToCart(course)}
                      disabled={getAvailableSlots(course) === 0 || cart.some(c => c.id === course.id)}
                    >
                      <ShoppingCart className="mr-1 h-3 w-3" />
                      {cart.some(c => c.id === course.id) ? '已添加' : '加入选课车'}
                    </Button>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>

        <TabsContent value="cart" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center">
                <ShoppingCart className="mr-2 h-5 w-5" />
                选课车
              </CardTitle>
            </CardHeader>
            <CardContent>
              {cart.length === 0 ? (
                <div className="text-center py-8 text-muted-foreground">
                  <ShoppingCart className="mx-auto h-12 w-12 mb-4" />
                  <p>选课车为空，请先添加课程</p>
                </div>
              ) : (
                <div className="space-y-4">
                  {cart.map((course) => (
                    <div key={course.id} className="flex items-center justify-between p-4 border rounded-lg">
                      <div>
                        <h4 className="font-medium">{course.name}</h4>
                        <p className="text-sm text-muted-foreground">
                          {course.teacher} · {course.credits}学分 · {course.time}
                        </p>
                      </div>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => removeFromCart(course.id)}
                      >
                        移除
                      </Button>
                    </div>
                  ))}
                  
                  <div className="pt-4 border-t">
                    <div className="flex justify-between items-center mb-4">
                      <span className="font-medium">总学分: {getTotalCredits()}</span>
                      {getTotalCredits() > 25 && (
                        <Badge variant="destructive">超出学分上限</Badge>
                      )}
                    </div>
                    
                    <Button 
                      className="w-full" 
                      disabled={cart.length === 0 || getTotalCredits() > 25}
                    >
                      <CheckCircle className="mr-2 h-4 w-4" />
                      提交选课
                    </Button>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="selected" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center">
                <CheckCircle className="mr-2 h-5 w-5" />
                已选课程
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {selectedCourses.map((course) => (
                  <div key={course.id} className="flex items-center justify-between p-4 bg-green-50 border border-green-200 rounded-lg">
                    <div>
                      <h4 className="font-medium">{course.name}</h4>
                      <p className="text-sm text-muted-foreground">
                        {course.teacher} · {course.credits}学分 · {course.time} · {course.location}
                      </p>
                    </div>
                    <div className="flex items-center space-x-2">
                      <Badge>已选中</Badge>
                      <Button variant="outline" size="sm">
                        <XCircle className="mr-1 h-3 w-3" />
                        退选
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}